# -*-coding: Utf-8 -*-
# @File : SMS_Ten_Send .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/8/9
import os

# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
import random
from . import settings


def get_verify_code(circle_bum):
    code = ''
    for i in range(circle_bum):
        code += str(random.randint(0, 9))
    return code


class SMS_TencentCloud_Sender():
    def __init__(self, code, phone):
        # 初始化 SecretId、SecretKey (为了安全防盗，置于本地环境变量中获取)
        self.cred = credential.Credential(settings.SECRET_ID, settings.SECRET_KEY)
        # 下发手机号码 : 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号
        self.phone = phone
        # 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，，若无模板参数，则设置为空
        # 验证码发送成功，验证码为：{self.code}，{self.timeout}分钟内有效！
        # 目标验证码 , 目标超时时间(如果模板中设置了有效时间)
        self.template_param_set = [f'{code}', f'{settings.FAIL_TIME}']
        # APPID : 添加应用后生成的实际SdkAppId,示例如1400006666
        self.appid = settings.SMS_SDK_APPID
        # 必须填写已审核通过的签名
        self.sign_name = settings.SIGN_NAME
        # 必须填写已审核通过的模板 ID
        self.template_id = settings.TEMPLATE_ID

    def create_Client(self):
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间，单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 实例化一个客户端配置对象，可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息，可以直接填写字符串ap-guangzhou
        # 支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        self.client = sms_client.SmsClient(self.cred, "ap-guangzhou", clientProfile)

    def create_Request(self):
        # 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
        req = models.SendSmsRequest()

        req.SmsSdkAppId = self.appid

        req.SignName = self.sign_name
        req.TemplateId = self.template_id
        req.TemplateParamSet = self.template_param_set
        req.PhoneNumberSet = [f"+86{self.phone}"]
        # 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回
        req.SessionContext = ""
        # 短信码号扩展号（无需要可忽略）: 默认未开通，如需开通请联系 [腾讯云短信小助手]
        req.ExtendCode = ""
        # 国内短信无需填写该项；国际/港澳台短信已申请独立 SenderId 需要填写该字段，默认使用公共 SenderId，无需填写该字段。
        req.SenderId = ""

        resp = self.client.SendSms(req)

        # 输出json格式的字符串回包
        res_dict = resp._serialize(allow_none=True)
        if res_dict['SendStatusSet'][0]['Code'] == "Ok":
            return True
        else:
            print(res_dict)
            return False

    def send_sms(self):
        self.create_Client()
        return self.create_Request()


def tencent_sms_main(verify_code, tag_phone):
    try:
        t_sms = SMS_TencentCloud_Sender(verify_code, tag_phone)
        return t_sms.send_sms()
    except Exception as e:
        print(e)
        return False


if __name__ == '__main__':
    phone = 13253184923
    code = get_verify_code(4)
    result = tencent_sms_main(code, phone)
    print(result)
    # print(os.environ)
